package com.rzico.sbl.ui.report.depot

import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDepotOrderBinding
import com.rzico.sbl.model.OrderData
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportDepotViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ReportDepotOrderActivity : BaseActivity(R.layout.activity_report_depot_order) {

    private val mBinding by lazy { ActivityReportDepotOrderBinding.bind(getRootView()) }

    override fun getViewModel() = get<ReportDepotViewModel>()

    override fun initData() {
        initTitle(title = "订单列表")

        initLayout()

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关订单信息！"
                }

                swipeRefresh.isEnabled = false

                recycleList.also { view ->
                    view.loadLinear(
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<OrderData>(R.layout.item_report_depot_order) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_depot_time, bean.createDate.getTimeString())
                                text(R.id.item_depot_name, bean.name)
                                text(R.id.item_depot_total, bean.quantity)
                                text(R.id.item_depot_sn, bean.sn)

                                visibility(
                                    R.id.item_depot_status,
                                    visibleValue { bean.printStatus == "已选择" }
                                )

                                with<LinearLayout>(R.id.item_depot_content) { layout ->
                                    layout.removeAllViews()

                                    bean.orderItems.forEach {
                                        layout.addView(
                                            inflate<View>(R.layout.content_report_depot_order).apply {
                                                find<TextView>(R.id.conent_title).text = it.name
                                                find<TextView>(R.id.conent_num).text = it.quantity
                                            }
                                        )
                                    }
                                }

                                image(
                                    R.id.item_depot_check,
                                    when {
                                        bean.printStatus == "已选择" -> R.mipmap.login_disable
                                        bean.check -> R.mipmap.login_yes_orange
                                        else -> R.mipmap.login_no
                                    }
                                )

                                clicked(R.id.item_depot_check) {
                                    (bean.printStatus == "已选择")
                                        .conditionElse(
                                            actionTrue = { showToast("已合并订单无法选择") },
                                            actionFalse = {
                                                bean.check = !bean.check
                                                notifyItemChanged(index)

                                                checkTotal()
                                            }
                                        )
                                }

                                clicked(R.id.item_depot) {
                                    goToOrderDetail("orderSn" to bean.sn)
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            orderSure.oneClick {
                mList.none { (it as OrderData).check }
                    .condition {
                        showToast("请选择要合并的订单")
                        return@oneClick
                    }

                getViewModel()
                    .request(
                        requestUrl = ReportUrl.getBaseUrl().depotSave,
                        params = arrayOf(
                            "id" to intent.getExtra("groupId"),
                            "ids" to mList
                                .filter { (it as OrderData).check }
                                .joinToString(",") { (it as OrderData).id }
                        ),
                        onSuccess = {
                            // 刷新出库列表
                            LiveEventBus
                                .get("depotOutList")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    /**
     * 合计选择数量
     */
    private fun checkTotal() {
        lifecycleScope.launch(Dispatchers.IO) {
            var totalCount = 0

            mList.filter { (it as OrderData).check }
                .forEach { item ->
                    item as OrderData

                    item.orderItems.forEach {
                        totalCount += it.quantity.intValue
                    }
                }

            withContext(Dispatchers.Main) {
                mBinding.orderSure.text = "确认合并(共${totalCount}件)"
            }
        }
    }

    /**
     * 司机订单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderList(
                page = index,
                isLoading = index == 0,
                memberId = intent.getExtra("memberId"),
                onSuccess = { list ->
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        intent.getExtra("orderSn")
                            .notEmpty {
                                list.filter { it.sn in this }
                                    .forEach {
                                        it.printStatus = ""
                                        it.check = true
                                    }
                            }

                        addItems(list)
                        list.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)

                    checkTotal()
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .emptyLayout
                        .emptyView
                        .isVisible = mList.isEmpty()
                }
            )
    }

}